﻿using Microsoft.Extensions.Caching.Memory;

namespace Project.Core.Config.Config.Cache {
    public class MemoryCacheHelper : ICacheHelper {

        private readonly IMemoryCache _cache;

        public MemoryCacheHelper(IMemoryCache cache) {
            this._cache = cache;
        }

        public TValue Get<TValue>(string key) {
            return _cache.Get<TValue>(key);
        }

        public List<TValue> Get<TValue>(List<string> keys) {
            List<TValue> list = new List<TValue>();
            foreach (string key in keys) {
                list.Add(_cache.Get<TValue>(key));
            }
            return list;
        }

        public bool IsExist(string key) {
            if (string.IsNullOrWhiteSpace(key)) {
                return false;
            } else {
                return _cache.TryGetValue(key, out _);
            }
        }

        public bool Remove(string key) {
            try {
                _cache.Remove(key);
                return true;
            } catch {
                return false;
            }
        }

        public bool Remove(List<string> keys) {
            try {
                foreach (string key in keys) {
                    _cache.Remove(key);
                }
                return true;
            } catch {
                return false;
            }
        }

        public bool Set<TValue>(string key, TValue value, int expires = 0, bool isSliding = false) {
            try {
                if (expires == 0) {
                    _cache.Set(key, value);
                } else {
                    if (isSliding) {
                        _cache.Set(key, value, new MemoryCacheEntryOptions {
                            SlidingExpiration = TimeSpan.FromSeconds(expires)
                        });
                    } else {
                        _cache.Set(key, value, new MemoryCacheEntryOptions {
                            AbsoluteExpiration = DateTime.Now.AddSeconds(expires)
                        });
                    }
                }
                return true;
            } catch {
                return false;
            }
        }
    }
}
